
from dao import ExcelHandler
from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from models.DonHang import DonHang
from utils.Const import TrangThaiDonHang
from utils.permission_required import permission_required
import WSGI
import json as simplejson
import logging
import math
import webapp2
from xlutils.xlwt import *

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiGiaoHangHomNay(webapp2.RequestHandler):
    priv = ''
    perm = 'GiaoHang.GiaoHangHomNay'
    @permission_required
    def get(self):
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/GiaoHangHomNay.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'GiaoHang.GiaoHangHomNay'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListGiaoHangHomNay': 'getListGiaoHangHomNay',
                       'printGiaoHang': 'printGiaoHang'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListGiaoHangHomNay(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        #rows, rowNum = DaoQuanLyNhanVien.getListGiaoHangHomNay(datetime.now().date(), gridRowNum, int((pageNum-1)*gridRowNum))
        query = DonHang.all().filter('trangThai in', [TrangThaiDonHang.KHOA, TrangThaiDonHang.DA_CO_HANG])
        query.filter('maNVGiaoHang !=', None)
        query.filter('duTru =', None)
        query.filter('ngayGiao1 =', (dt.now() + datetime.timedelta(hours=7)).date())
        lstDonHang = query.run()
        rows = []
        for dh in lstDonHang:
            row = {}
            flag = True
            for r in rows:
                if r['maNhanVien'] == dh.maNVGiaoHang:
                    r['donHangDat'] = r['donHangDat'] + ', ' + "<a href='/donhang/?id=" + str(dh.key().id()) + "'>" + str(dh.key().id()) + "</a>"
                    flag = False
                    break
            if flag == True:
                row['maNhanVien'] = dh.maNVGiaoHang
                row['tenNhanVien'] = str(dh.maNVGiaoHang) + ' - ' + dh.tenNVGiaoHang
                row['donHangDat'] = "<a href='/donhang/?id=" + str(dh.key().id()) + "'>" + str(dh.key().id()) + "</a>"
                row['inRa'] = "<a href='/giaohanghomnay/json/?func=printGiaoHang&id=" + str(dh.maNVGiaoHang) + "'>To excel</a>"
                rows.append(row) 
        rowNum = rows.__len__()
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
   
    def printGiaoHang(self):
#        maNV = self.request.get('id')
#        wb = ExcelHandler.exportGiaoHang(maNV)
#        self.response.headers['Content-Type'] = 'application/excel; charset=UTF-8'
#        wb.save(self.response.out)
#        self.response.out.write('123')
        self.response.headers['Content-Type'] = 'text/csv; charset=utf-16'
        self.response.headers['Content-Disposition'] = "attachment; filename=GiaoHang_" + (dt.now() + datetime.timedelta(hours=7)).date().strftime('%d-%m-%Y') + ".csv"
        maNV = self.request.get('id')
        content = ExcelHandler.exportGiaoHang(maNV)
        self.response.out.write(content)
        
        
            
        